﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using ServiceAuthJwt.Model;
using UtilsCache;
using ServiceAuthJwt.Auth;
using Nancy;
using System.Security.Claims;
using ServiceAuthJwt.Web;

namespace JWTLogin.Controllers
{
    [ApiController]
    [Route("[controller]/[action]")]
    public class AuthController : ControllerBase
    {
        public ActionResult Get()
        {
            return Ok(1);
        }

        public ActionResult RequestToken(int userid)
        {
            DTOLoginRequest request = new DTOLoginRequest();
            request.UserId = userid;
            request.Username = "admin";
            request.Password = "123456";
            Dictionary<string, string> keyValuePairs = new TokenAuthenticationService().createToken(request);
            return Ok(keyValuePairs);
            //return BadRequest("Invalid Request");
        }

        public ActionResult RefreshToken(string refreshToken, string userId)
        {
            string _refreshToken = UtilMemoryCacheHelper.get<string>("refreshToken" + userId);
            if (_refreshToken == refreshToken)
            {
                string json = UtilMemoryCacheHelper.get<string>("DTOLoginRequest" + userId);
                DTOLoginRequest request = JsonConvert.DeserializeObject<DTOLoginRequest>(json);
                Dictionary<string, string> keyValuePairs = new TokenAuthenticationService().createToken(request);
                return Ok(keyValuePairs);
            }
            return Ok();
        }

        [Authorize]
        public ActionResult GetUser()
        {
            // 获取用户ID
            var userId = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier)?.Value;

            // ...
            return Ok(new { UserId = userId });
           // return Ok(new { Name = principal.GetUserId(), Power = new string[] { "1", "2" } });
        }

       


        
    }
}
